﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Sustainalytics.Admin.Synchronization.Utility;
using Sustainalytics.ESGRatings.DataContract.ESG;
using Sustainalytics.ReportGenerator.BL;

namespace Sustainalytics.ESGRatings.BusinessLogic.ESGClient
{
    public class ESGRatingsComputationsClient
    {
        private readonly ESGClient esgClient;

        private readonly Entities.ESGRatings.ESGProfile profile;

        private readonly Lazy<Task<ESGRatingsAdapter>> esgRatingsLazy;

        public ESGRatingsComputationsClient(string esgComputeResourceAddress, Entities.ESGRatings.ESGProfile profile, Guid setId)
        {
            Guard.ArgumentNotNull(profile, "profile");
            Guard.ArgumentNotNullOrEmpty(esgComputeResourceAddress, "esgComputeResourceAddress");

            this.profile = profile;
            esgClient = new ESGClient(esgComputeResourceAddress);
            esgRatingsLazy = new Lazy<Task<ESGRatingsAdapter>>(() => BuildEsgRatingsLazy(setId), LazyThreadSafetyMode.ExecutionAndPublication);
        }

        public Task<ESGRatingsAdapter> GetRatingsAsync()
        {

            return esgRatingsLazy.Value;
        }

        private async Task<ESGRatingsAdapter> BuildEsgRatingsLazy(Guid setId)
        {
            var options = new ESGRatingsOptionsDto
            {
                RefUnivId = profile.ReferenceUniverseId,
                MatrixId = profile.MatrixId,
                IncludeTopPerformersInfo = true,
                IncludeAggregatedScores = true,
                IncludeRatings = true,
                IncludeWeights = true,
                IncludeAggregatedWeights = true,
                IncludeIndWeightedScores = true,
                IncludeCompaniesInGroup = true,
                GroupBy = profile.ComparativeGroup,
                CompanyType = profile.CompanyType,
                TemplateType = profile.TemplateType,
                SetId = setId
            };

                
            var result = await esgClient.GetRatings(options);

            return new ESGRatingsAdapter(result);
        }


    }
}